package org.statemachine.service;

import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.stereotype.Component;
import org.statemachine.config.OrderEvents;
import org.statemachine.domain.Order;

@Slf4j
@Component
public class OrderProcessor {
    @Resource
    private StateMachine orderStateMachine;


    @Resource
    private StateMachinePersister persist;


    public boolean process(Order order, OrderEvents event) {
        Message<OrderEvents> message = MessageBuilder.withPayload(event).setHeader("order", order).build();
        boolean b = sendEvent(message);
        return b;
    }

    @SneakyThrows
    private boolean sendEvent(Message<OrderEvents> message) {
        Order order = (Order) message.getHeaders().get("order");
        persist.restore(orderStateMachine, order);
        boolean result = orderStateMachine.sendEvent(message);
        return result;
    }
}
